package com.wsoft.config;

import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.spi.JobFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.scheduling.quartz.SpringBeanJobFactory;

/**
 * @Author z001
 * @Date 2024/11/26 09:51
 */
@Configuration
public class QuartzConfig {
    @Autowired
    private ApplicationContext applicationContext;
    @Autowired
    private JobFactory jobFactory;
    @Bean
    public JobFactory jobFactory() {
        SpringBeanJobFactory jobFactory = new SpringBeanJobFactory();
        jobFactory.setApplicationContext(applicationContext);
        return jobFactory;
    }

    @Bean
    public SchedulerFactoryBean schedulerFactoryBean() {
        SchedulerFactoryBean factory = new SchedulerFactoryBean();
        // 使用 SpringBeanJobFactory
        factory.setJobFactory(jobFactory);
        return factory;
    }

    @Bean
    public CustomJobListener myJobListener() {
        return new CustomJobListener();
    }
    @Bean
    public CustomSchedulerListener mySchedulerListener() {
        return new CustomSchedulerListener();
    }

    @Bean
    public Scheduler scheduler(SchedulerFactoryBean schedulerFactoryBean) throws SchedulerException {
        Scheduler scheduler = schedulerFactoryBean.getScheduler();
        // 注册 JobListener
        scheduler.getListenerManager().addJobListener(myJobListener());
        // 注册  mySchedulerListener
        scheduler.getListenerManager().addSchedulerListener(mySchedulerListener());
        return scheduler;
    }



}
